package Netty.old.NIONetty.群聊系统;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class GroupChatServer {
    private int port;//监听端口
    public GroupChatServer(int port){
        this.port=port;
    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer(7000);
        groupChatServer.run();

    }

    public void run() {//编写run方法
        //创建两个线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);//专门负责接受客户端的连接
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(8);//专门负责网络的编写
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)//使用NioServerSocketChannel做通道实现
                    .option(ChannelOption.SO_BACKLOG,128)//设置线程队列连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE,true)//设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();//获取pipeline
                            pipeline.addLast("decode",new StringDecoder());//加入解码器
                            pipeline.addLast("encode",new StringEncoder());//加入编码器
                            pipeline.addLast(new GroupChatServerHandler());//加入自己的业务处理handler
                        }
                    });
            System.out.println("netty服务器启动");

            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();//关闭监听
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
}
